const Koa = require('koa2');
const Router = require('koa-router')
const path = require('path')
const staticFiles = require('koa-static')
const router = new Router()
const app = new Koa();


const sequelize = require('./config/newDb.js')
const dbm = require('./config/dbModels.js')


const catchError = require('./middlewares/exception');//一旦抛出错误,被middlewares/exception捕获

const cors = require('@koa/cors')//允许ajax跨域



const koaBody = require('koa-body')//令koa2支持post方法


const errors = require('./core/http-exception.js')
global.errs = errors;


app.use(cors())
app.use(catchError);//一旦抛出错误,被middlewares/exception捕获
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 2*1024*1024	// 设置上传文件大小最大限制，目前设为2M,0.1MB=102.4kb
    },
    onError: function () { 
        throw new global.errs.ParameterException('文件太大')
    }
}));
app.use(staticFiles(__dirname + '/public/'));

const registerRouter  = require('./routes')
/*
加密及校验资料,无法解密
https://www.cnblogs.com/yaogengzhu/p/11028840.html
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
*/






/**
  sequelize.beforeConnect((config) => {
    console.log('拉拉',config)
 })
 */
sequelize.authenticate()
    .then(() => {
        console.log('数据库连接成功');
    })
    .catch(err => {
        console.log('失败,数据库连接失败', err)
    })


//console.log(`当前node环境${process.env.NODE_ENV}`);






// app
//     .use(router.routes())
//     .use(router.allowedMethods());
    app.use(registerRouter())
/*

app.use(async (ctx, next) => {
    router.get('/', async function (ctx, next) {
        ctx.state = {
          title: 'koa2 title'
        };
    
        await ctx.render('welcome', {title: ctx.state});
      })

    // console.log(`查看参数${ctx.request.querystring}`); // 
    // console.log(`第1个`); // 
    // console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    // await next(); // 调用下一个middleware
});
*/

/*

router
.get('/', (ctx, next) => {
    ctx.body = 'Hello World!';
})
.get('/cd', (ctx, next) => {
    //ctx.body = 'Hccccckkkkk!';
    ctx.state = {
        title: 'koa2 title'
      };
       ctx.render('welcome', {title: ctx.state});
})
.get('*', (ctx, next) => {
    ctx.body = '404444!';
  })
  
*/


// app.use(router.routes()).use(router.allowedMethods());

/*
app.use(async (ctx, next) => {
    console.log(`第2个`);
    const start = new Date().getTime(); // 当前时间
    await next(); // 调用下一个middleware
    const ms = new Date().getTime() - start; // 耗费时间
    ctx.set('X-Response-Time', `${ms}ms`);
    console.log(`哇Time: ${ms}ms`); // 打印耗费时间
});
*/

/*
app.use(async (ctx, next) => {
    console.log(`第3个`); 
    ctx.response.type = 'text/html';
    ctx.cookies.set('abb',99)
    ctx.response.body = '<h1>Hello, koa2!</h1>';
    await next();
});

*/

app.listen(3000);